import com.rabbitmq.client.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;




public class rpcServer {

	private static final String RPC_QUEUE_NAME = "rpc_queue";
	//private static final String rabbitmqServer = "localhost";
	//private static final String rabbitmqServer = "us01l-david1.am.mt.mtnet";
	private static final String rabbitmqServer = "us01s-netops01";
	//private static final String rabbitmqServer = "rp-1";
	
	
	@SuppressWarnings("deprecation")
	public static void main(String[] argv) throws Exception {
	//public void RPCServer() throws Exception {
	ConnectionFactory factory = new ConnectionFactory();
	
	factory.setHost(rabbitmqServer);

	Connection connection = factory.newConnection();
	Channel channel = connection.createChannel();

	channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

	channel.basicQos(1);

	QueueingConsumer consumer = new QueueingConsumer(channel);
	channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

	System.out.println(" [x] Awaiting RPC requests");

	while (true) {
	    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
	    System.out.println("got something");
	    BasicProperties props = delivery.getProperties();


	    AMQP.BasicProperties replyprops = new AMQP.BasicProperties();
	   // replyprops.getCorrelationId(props.getCorrelationId());
	    replyprops.setCorrelationId(props.getCorrelationId());
	    replyprops.setReplyTo(RPC_QUEUE_NAME);
	    
	    
	    String message = new String(delivery.getBody());
	    //int n = Integer.parseInt(message);

	    System.out.println(message);
	   // String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
	    
	   // String m = "m";
	    
	    String response = callex2(message);

	    channel.basicPublish( "", props.getReplyTo(), replyprops, response.getBytes());

	    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
	}
}

	
	public static String callex2(String message) throws Exception {
	
		try{
		Process p = Runtime.getRuntime().exec(message);
		
		BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

		String line;
		String line2 = "";
		
		while ((line = input.readLine()) != null) {
		  line2 = line2 + "\n" + line;
		}
		
		return line2;
		

		}catch( IOException ex ){
	    return ex.toString();	
		//Validate the case the file can't be accesed (not enought permissions)
	}	
	}		
}

